package com.demo.service;

import com.demo.repository.RoleRepository;
import com.demo.repository.UserRepository;
import mapper.RoleBean;
import mapper.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.faces.context.FacesContext;
import java.util.ArrayList;

/**
 * User: yuebo
 * Date: 13-9-1
 * Time: 下午3:54
 */
@Service
public class AuthenticationService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserRepository userRepository ;

    public void setRoleRepository(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }

    @Autowired
    private RoleRepository roleRepository ;

    @Autowired
    PasswordEncoder passwordEncoder;

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public boolean login(String username,String password){
        try{
            Authentication authentication= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, passwordEncoder.encodePassword(password,password)));
            if(authentication.isAuthenticated()){
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return true;
            }
        }catch (AuthenticationServiceException e){
            return false;
        }catch (BadCredentialsException exception){
            return false;
        }


        return false;
    }

    public void initApplication(){
        if(userRepository.findByUsername("xyb")==null){
            final RoleBean roleBean=new RoleBean();
            roleBean.setRoleName("User");
            roleRepository.save(roleBean);
            UserBean userBean=new UserBean();
            userBean.setUsername("xyb");
            userBean.setPassword(passwordEncoder.encodePassword("xyb", "xyb"));
            userBean.setRoles(new ArrayList() {{
                add(roleBean);
            }});
            userRepository.save(userBean);
        }

    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
}
